package com.qg.auth.handler.impl;

import cn.hutool.core.bean.BeanUtil;
import com.qg.auth.handler.WebContextHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author QG
 * @Date 2023/5/25 11:07
 * @description cookie、session会话方式实现
 **/
@Component("webContextHandler")
@ConditionalOnProperty(name = "system.login.method", havingValue = "session", matchIfMissing = false)
public class WebContextSession implements WebContextHandler {

    private static final Logger logger = LoggerFactory.getLogger(WebContextSession.class);

    @Value("${spring.application.name:app}")
    private String APP_NAME;

    private final String PREFIX_USER = "user:";


    /**
     * 获取用户信息
     * @param clazz 用户信息类文件
     * @return 用户信息
     * @param <T>
     */
    @SuppressWarnings({"unchecked" })
    @Override
    public <T> T getUser(Class<T> clazz) {
        String userKey = PREFIX_USER + APP_NAME + ":" + getSession().getId();
        return (T)getSession().getAttribute(userKey);
    }

    @Override
    public Map getUser() {

        String token = getTokenString(getRequest());
        Object user = getRequest().getSession().getAttribute(token);
        if(user == null) {
            return null;
        }
        Map<String, Object> map = BeanUtil.beanToMap(user);
        return map;
    }

    @Override
    public String getTokenString(HttpServletRequest request) {
        String sessionId = request.getSession().getId();
        String userKey = PREFIX_USER + APP_NAME + ":" + sessionId;
        return userKey;
    }

    @Override
    public String setUser(Object user) {
        String sessionId = getSession().getId();
        String userKey = PREFIX_USER + APP_NAME + ":" + sessionId;
        getSession().setAttribute(userKey,user);
        return sessionId;
    }

    @Override
    public void setUser(String token) {
        logger.debug("该方法尚未实现，目前为空实现");
    }

    @Override
    public void removeUser() {
        String sessionId = getSession().getId();
        String userKey = PREFIX_USER + APP_NAME + ":" + sessionId;
        getRequest().getSession().removeAttribute(userKey);
    }


}
